import React, { useState, useEffect } from 'react';
import { Modal, Form, Select, Input, message, Radio, Button } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { getAllSysConf } from '../../api/directoryManagement';

interface ManualArchiveModalProps {
  visible: boolean;
  onClose: () => void;
}

const ManualArchiveModal: React.FC<ManualArchiveModalProps> = ({ visible, onClose }) => {
  const [loading, setLoading] = useState(false);
  const [selectedTask, setSelectedTask] = useState('');
  const [archivePath, setArchivePath] = useState('');
  const [archiveType, setArchiveType] = useState<'standard' | 'nonstandard'>('standard');
  const [taskOptions, setTaskOptions] = useState<Array<{label: string, value: string}>>([]);
  const [loadingTasks, setLoadingTasks] = useState(false);
  const [selectedNonstandardTask, setSelectedNonstandardTask] = useState('');
  const [downloadingTemplate, setDownloadingTemplate] = useState(false);

  // 获取任务选项
  useEffect(() => {
    const fetchTaskOptions = async () => {
      if (!visible) return;  // 只有弹窗打开时才获取

      setLoadingTasks(true);
      try {
        const result = await getAllSysConf();
        if (result.success && result.data?.ROLL) {
          // 获取 ROLL 对象的所有 key 作为任务选项
          const rollKeys = Object.keys(result.data.ROLL);
          const options = rollKeys.map(key => ({
            label: key,  // 直接使用 key 作为显示文本
            value: key   // 直接使用 key 作为值
          }));
          setTaskOptions(options);

          // 设置默认选择
          if (options.length > 0) {
            // 标准归档：选择第一个选项
            setSelectedTask(options[0].value);

            // 非标准归档：优先选择TW2，否则选择ALL
            const hasTW2 = options.some(option => option.value === 'TW2');
            if (hasTW2) {
              setSelectedNonstandardTask('TW2');
            } else {
              setSelectedNonstandardTask('ALL');
            }
          }
        } else {
          console.warn('获取系统配置失败或ROLL数据为空');
          setTaskOptions([]);
          setSelectedTask('');
          setSelectedNonstandardTask('');
        }
      } catch (error) {
        console.error('获取任务选项失败:', error);
        message.error('获取任务选项失败，请重试');
        setTaskOptions([]);
        setSelectedTask('');
        setSelectedNonstandardTask('');
      } finally {
        setLoadingTasks(false);
      }
    };

    fetchTaskOptions();
  }, [visible]);  // 依赖 visible，弹窗打开时重新获取

  // 下载模板
  const handleDownloadTemplate = async () => {
    if (!selectedNonstandardTask) {
      message.error('请先选择任务');
      return;
    }

    setDownloadingTemplate(true);
    try {
      const token = localStorage.getItem('token') || '';
      const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

      const response = await fetch(`${API_BASE_URL}/-/bin.manualArchiving.download_manual_mould`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'token': token
        },
        body: JSON.stringify({
          task: selectedNonstandardTask
        })
      });

      if (!response.ok) {
        throw new Error(`下载失败: ${response.statusText}`);
      }

      // 处理文件下载
      const blob = await response.blob();
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${selectedNonstandardTask}_手动归档模板.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);

      message.success('模板下载成功');
    } catch (error) {
      console.error('下载模板失败:', error);
      if (error instanceof Error) {
        message.error(`下载失败: ${error.message}`);
      } else {
        message.error('下载模板失败，请重试');
      }
    } finally {
      setDownloadingTemplate(false);
    }
  };

  const handleSubmit = async () => {
    // 标准归档需要验证任务选择
    if (archiveType === 'standard') {
      if (!selectedTask) {
        message.error('请选择任务');
        return;
      }
    }
    
    if (!archivePath.trim()) {
      message.error('请输入文件路径');
      return;
    }

    setLoading(true);
    try {
      const token = localStorage.getItem('token') || '';
      const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
      
      let response;
      if (archiveType === 'standard') {
        // 标准数据手动归档
        response = await fetch(`${API_BASE_URL}/-/bin.manualArchiving.add_norm_archiving`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'token': token
          },
          body: JSON.stringify({
            task: selectedTask,
            path: archivePath.trim()
          })
        });
      } else {
        // 非标准数据手动归档
        response = await fetch(`${API_BASE_URL}/-/bin.manualArchiving.add_manual_archiving`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'token': token
          },
          body: JSON.stringify({
            path: archivePath.trim()
          })
        });
      }

      if (!response.ok) {
        throw new Error(`API调用失败: ${response.statusText}`);
      }

      const result = await response.json();
      
      if (result && (result.code === 0 || result.code === 200)) {
        message.success('手动归档任务提交成功');
        handleClose();
      } else {
        message.error(`归档失败: ${result.msg || '未知错误'}`);
      }
    } catch (error) {
      console.error('手动归档失败:', error);
      // 由于error类型为unknown，需要类型保护
      if (error instanceof Error) {
        message.error(`归档失败: ${error.message}`);
      } else if (typeof error === 'string') {
        message.error(`归档失败: ${error}`);
      } else {
        message.error('归档失败: 未知错误');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setSelectedTask('');
    setSelectedNonstandardTask('');
    setArchivePath('');
    setArchiveType('standard');
    setTaskOptions([]);
    setLoadingTasks(false);
    setDownloadingTemplate(false);
    onClose();
  };

  return (
    <Modal
      title="手动归档"
      open={visible}
      onOk={handleSubmit}
      onCancel={handleClose}
      confirmLoading={loading}
      okText="开始归档"
      cancelText="取消"
      width={600}
    >
      <Form layout="vertical">
        <Form.Item 
          label="归档类型" 
          required
        >
          <Radio.Group 
            value={archiveType} 
            onChange={(e) => setArchiveType(e.target.value)}
          >
            <Radio value="standard">标准数据手动归档</Radio>
            <Radio value="nonstandard">非标准数据手动归档</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item 
          label={archiveType === 'standard' ? '任务' : '任务选择'}
          required={archiveType === 'standard'}
          help={archiveType === 'standard' ? '请选择要归档的任务类型' : '请选择任务并下载对应模板'}
        >
          {archiveType === 'standard' ? (
            <Select
              value={selectedTask}
              onChange={setSelectedTask}
              placeholder="请选择任务"
              style={{ width: '100%' }}
              loading={loadingTasks}
              notFoundContent={loadingTasks ? '加载中...' : '暂无任务选项'}
              disabled={loadingTasks}
            >
              {taskOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
              <Select
                value={selectedNonstandardTask}
                onChange={setSelectedNonstandardTask}
                placeholder="请选择任务"
                style={{ width: '100%' }}
                loading={loadingTasks}
                notFoundContent={loadingTasks ? '加载中...' : '暂无任务选项'}
                disabled={loadingTasks}
              >
                <Select.Option key="ALL" value="ALL">
                  ALL
                </Select.Option>
                {taskOptions.map(option => (
                  <Select.Option key={option.value} value={option.value}>
                    {option.label}
                  </Select.Option>
                ))}
              </Select>
              <Button
                icon={<DownloadOutlined />}
                onClick={handleDownloadTemplate}
                type="primary"
                ghost
                disabled={!selectedNonstandardTask || downloadingTemplate}
                loading={downloadingTemplate}
              >
                下载模板
              </Button>
            </div>
          )}
        </Form.Item>
        
        <Form.Item 
          label="文件路径" 
          required
          help="请输入需要归档的文件或目录的完整路径"
        >
          <Input.TextArea
            value={archivePath}
            onChange={(e) => setArchivePath(e.target.value)}
            placeholder="例如：/DMSWORK"
            rows={3}
            maxLength={500}
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ManualArchiveModal;